package com.xzw.cameratest.activty;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.MediaScannerConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.constraint.ConstraintLayout;
import android.support.v4.widget.NestedScrollView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.business.adapter.DataAdapterImpl;
import com.android.business.adapter.DataAdapterInterface;
import com.android.business.entity.ChannelInfo;
import com.android.business.entity.UserInfo;
import com.android.business.entity.VictoryKey;
import com.android.business.exception.BusinessException;
import com.android.dahua.dhplaycomponent.IMediaPlayListener;
import com.android.dahua.dhplaycomponent.IOperationListener;
import com.android.dahua.dhplaycomponent.IPTZListener;
import com.android.dahua.dhplaycomponent.ITalkListener;
import com.android.dahua.dhplaycomponent.PlayManagerProxy;
import com.android.dahua.dhplaycomponent.audiotalk.param.CloudBaseTalk;
import com.android.dahua.dhplaycomponent.audiotalk.param.DPSTalk;
import com.android.dahua.dhplaycomponent.audiotalk.param.ExpressTalk;
import com.android.dahua.dhplaycomponent.audiotalk.param.TalkParam;
import com.android.dahua.dhplaycomponent.audiotalk.param.inner.CloudBaseTalkParam;
import com.android.dahua.dhplaycomponent.audiotalk.param.inner.DPSTalkParam;
import com.android.dahua.dhplaycomponent.audiotalk.param.inner.ExpressTalkParam;
import com.android.dahua.dhplaycomponent.camera.RTCamera.CloudBaseRTCamera;
import com.android.dahua.dhplaycomponent.camera.RTCamera.CloudBaseRTCameraParam;
import com.android.dahua.dhplaycomponent.camera.RTCamera.DPSRTCamera;
import com.android.dahua.dhplaycomponent.camera.RTCamera.DPSRTCameraParam;
import com.android.dahua.dhplaycomponent.camera.RTCamera.ExpressRTCamera;
import com.android.dahua.dhplaycomponent.camera.RTCamera.ExpressRTCameraParam;
import com.android.dahua.dhplaycomponent.camera.inner.Camera;
import com.android.dahua.dhplaycomponent.camera.inner.RealInfo;
import com.android.dahua.dhplaycomponent.common.Err;
import com.android.dahua.dhplaycomponent.common.PlayStatusType;
import com.android.dahua.dhplaycomponent.common.PtzOperation;
import com.android.dahua.dhplaycomponent.common.PtzZoomState;
import com.android.dahua.dhplaycomponent.common.RecordType;
import com.android.dahua.dhplaycomponent.common.TalkResultType;
import com.android.dahua.dhplaycomponent.windowcomponent.entity.ControlType;
import com.android.dahua.dhplaycomponent.windowcomponent.window.PlayWindow;
import com.dahua.permission.PermissionUtil;
import com.dahua.permission.constant.PermissionConstant;
import com.xzw.cameratest.BuildConfig;
import com.xzw.cameratest.R;
import com.xzw.cameratest.async.AsyncBuilder;
import com.xzw.cameratest.base.BaseActivity;
import com.xzw.cameratest.common.CommonInfo;
import com.xzw.cameratest.common.Config;
import com.xzw.cameratest.fragment.PresetPositionDialogFragment;
import com.xzw.cameratest.utils.Base64Utils;
import com.xzw.cameratest.utils.FileStorageUtil;
import com.xzw.cameratest.utils.SPUtils;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class PlayOnlineActivity extends BaseActivity implements PermissionUtil.OnPermissionRequestListener, View.OnTouchListener, View.OnClickListener {

    private ImageView mIvBack;
    private ConstraintLayout mClTitle;
    private PlayWindow mPlayWindow;
    private TextView mTvChannelName;
    private ImageView mIvFullScreen;
    private TextView mTvScreenshots;
    private TextView mTvVideotape;
    private TextView mTvIntercom;
    private TextView mTvPresetPosition;
    private TextView mTvPtz;
    private ImageView mMultipleSubtract;
    private ImageView mMultipleAdd;
    private ImageView mFocalLengthSubtract;
    private ImageView mFocalLengthAdd;
    private ImageView mApertureSubtract;
    private ImageView mApertureAdd;
    private NestedScrollView mNestedScrollView;

    private static final String TAG = "PlayOnlineActivity";
        public static final int Stream_Main_Type = 1;        //主码流 // the main stream
    public static final int Stream_Assist_Type = 2;        //辅码流 // auxiliary stream
//    public static final int Stream_Third_Type = 3;        //三码流 // three stream

    public static final int KEY_Handler_Stream_Played = 1;
    public static final int KEY_Handler_First_Frame = 2;
    public static final int KEY_Handler_Net_Error = 3;
    public static final int KEY_Handler_Play_Failed = 4;

    public static final String KEY_PlayOnline_ChannelInfo = "channelInfo";
    protected PlayManagerProxy mPlayManager;
    private DataAdapterInterface dataAdapterInterface;
    private ChannelInfo mChannelInfo;
    private List<ChannelInfo> channelInfoList = new ArrayList<>();
    private String encryptKey = "";
    private int mScreenHeight;
    private int mScreenWidth;
    private int mPermission;
    private boolean isFull = false;
    private boolean isStartTalk = false;
    private boolean isPlaying = false;
    protected String[] recordPath;
    private PermissionUtil permissionUtil;

    @SuppressLint("HandlerLeak")
    protected Handler mPlayOnlineHander = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case KEY_Handler_Stream_Played:
                    isPlaying = true;
                    int winIndex = (Integer) msg.obj;

                    if (winIndex != mPlayManager.getSelectedWindowIndex()) return;
                    if (channelInfoList != null && channelInfoList.size() == 1) {
                        mPlayManager.maximizeWindow(winIndex);
                        mPlayManager.setEZoomEnable(winIndex, true);
                    }
//                    if (mPlayManager.isNeedOpenAudio(winIndex))
                    openAudio(winIndex);
                    break;
                case KEY_Handler_First_Frame:
                    mPlayManager.playCurpage();
                    break;
                case KEY_Handler_Net_Error:
                case KEY_Handler_Play_Failed:
                    isPlaying = false;
                    winIndex = (Integer) msg.obj;
                    stopPlay(winIndex);
                    break;
            }
        }
    };

    public static void open(Context context, ChannelInfo channelInfo) {
        Intent intent = new Intent(context, PlayOnlineActivity.class);
        intent.putExtra(KEY_PlayOnline_ChannelInfo, channelInfo);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    @Override
    protected int initContentView() {
        return R.layout.activity_play_online;
    }

    @Override
    protected void initView() {
        mIvBack = findViewById(R.id.iv_back);
        mClTitle = findViewById(R.id.cl_title);
        mPlayWindow = findViewById(R.id.playWindow);
        mTvChannelName = findViewById(R.id.tv_channel_name);
        mIvFullScreen = findViewById(R.id.iv_full_screen);
        mTvScreenshots = findViewById(R.id.tv_screenshots);
        mTvVideotape = findViewById(R.id.tv_videotape);
        mTvIntercom = findViewById(R.id.tv_intercom);
        mTvPresetPosition = findViewById(R.id.tv_preset_position);
        mTvPtz = findViewById(R.id.tv_ptz);
        mMultipleSubtract = findViewById(R.id.multiple_subtract);
        mMultipleAdd = findViewById(R.id.multiple_add);
        mFocalLengthSubtract = findViewById(R.id.focal_length_subtract);
        mFocalLengthAdd = findViewById(R.id.focal_length_add);
        mApertureSubtract = findViewById(R.id.aperture_subtract);
        mApertureAdd = findViewById(R.id.aperture_add);
        mNestedScrollView = findViewById(R.id.nestedScrollView);
        mIvBack.setOnClickListener(this);
        mIvFullScreen.setOnClickListener(this);
        mTvScreenshots.setOnClickListener(this);
        mTvVideotape.setOnClickListener(this);
        mTvIntercom.setOnClickListener(this);
        mTvPresetPosition.setOnClickListener(this);
        mTvPtz.setOnClickListener(this);
        findViewById(R.id.tv_playback).setOnClickListener(this);
    }

    @Override
    protected void initData() {
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        mScreenWidth = metric.widthPixels; // 屏幕宽度（像素）
        mScreenHeight = metric.heightPixels; // 屏幕高度（像素）
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void doSomething() {
        permissionUtil = new PermissionUtil(this);
        mChannelInfo = (ChannelInfo) getIntent().getSerializableExtra(KEY_PlayOnline_ChannelInfo);
        dataAdapterInterface = DataAdapterImpl.getInstance();
        mPlayManager = new PlayManagerProxy();
        //初始化窗口数量，默认显示4个窗口，最多16窗口，若设置单窗口均设置为1
        mPlayManager.init(this, mPlayWindow);
        //设置播放监听
        // set play monitor.
        mPlayManager.setOnMediaPlayListener(iMediaPlayListener);
        //设置窗口操作监听
        mPlayManager.setOnOperationListener(iOperationListener);

        // set the intercom monitor.
        mPlayManager.setOnTalkListener(new ITalkListener());
        mPlayManager.setLogEnable(true);
        //设置云台监听
        // set the cloud monitor.
        mPlayManager.setOnPTZListener(iptzListener);

        initCommonWindow();

        channelInfoList.add(mChannelInfo);

        mPlayManager.addCameras(getCameras());
        //判断设备是否支持云台功能
        mTvPtz.setVisibility(mChannelInfo.getCameraInputInfo() != null && mChannelInfo.getCameraInputInfo().getCameraType() == ChannelInfo.CameraType.CameraPtz ? View.VISIBLE : View.INVISIBLE);
        mMultipleSubtract.setOnTouchListener(this);
        mMultipleAdd.setOnTouchListener(this);
        mFocalLengthSubtract.setOnTouchListener(this);
        mFocalLengthAdd.setOnTouchListener(this);
        mApertureSubtract.setOnTouchListener(this);
        mApertureAdd.setOnTouchListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        replay();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopAll();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPlayManager != null) {
            mPlayManager.unitPlayManager();
            mPlayManager = null;
        }
    }

    private List<Camera> getCameras() {
        List<Camera> cameras = new ArrayList<>();
        if (channelInfoList != null) {
            for (ChannelInfo channelInfo : channelInfoList) {
                cameras.add(getCamera(channelInfo));
            }
        }
        return cameras;
    }

    public boolean openAudio(int winIndex) {

        return mPlayManager.openAudio(winIndex) == Err.OK;
    }

    private Camera getCamera(ChannelInfo channelInfo) {
        if (BuildConfig.dssPlatform == 1) {
            //创建播放Camera参数
            CloudBaseRTCameraParam cloudBaseCameraParam = new CloudBaseRTCameraParam();
            //设置窗口要播放的通道ID
            cloudBaseCameraParam.setCameraID(channelInfo.getChnSncode());
            //获取码流类型
            int mStreamType = ChannelInfo.ChannelStreamType.getValue(channelInfo.getStreamType());
            if (mStreamType > Stream_Assist_Type) mStreamType = Stream_Assist_Type;
            cloudBaseCameraParam.setStreamType(mStreamType - 1);
            cloudBaseCameraParam.setDpRestToken(CommonInfo.getInstance().getEnvironmentInfo().getRestToken());
            cloudBaseCameraParam.setServerIp(SPUtils.getString(Config.IP, ""));
            cloudBaseCameraParam.setServerPort(Integer.parseInt(SPUtils.getString(Config.PORT, "")));

            cloudBaseCameraParam.setRoute(false);
            cloudBaseCameraParam.setUserId("");
            cloudBaseCameraParam.setDomainId("");
            cloudBaseCameraParam.setRegionId("");
            cloudBaseCameraParam.setLocation("");

            cloudBaseCameraParam.setUseHttps(CommonInfo.getInstance().getEnvironmentInfo().isHttps() ? 1 : 0);

            return new CloudBaseRTCamera(cloudBaseCameraParam);
        } else if (BuildConfig.dssPlatform == 2) {
            getEncryptKey();
            ExpressRTCameraParam expressRTCameraParam = new ExpressRTCameraParam();
            expressRTCameraParam.setCameraID(channelInfo.getChnSncode());
            int mStreamType = ChannelInfo.ChannelStreamType.getValue(channelInfo.getStreamType());
            if (mStreamType > Stream_Assist_Type) {
                mStreamType = Stream_Assist_Type;
            }
            expressRTCameraParam.setStreamType(mStreamType);
            expressRTCameraParam.setDpRestToken(CommonInfo.getInstance().getEnvironmentInfo().getRestToken());
            expressRTCameraParam.setServerIP(SPUtils.getString(Config.IP, ""));
            expressRTCameraParam.setServerPort(Integer.parseInt(SPUtils.getString(Config.PORT, "")));

            if (!TextUtils.isEmpty(encryptKey)) {
                expressRTCameraParam.setEncrypt(true);
                expressRTCameraParam.setPsk(encryptKey);
            }
            expressRTCameraParam.setAuthorization(CommonInfo.getInstance().getEnvironmentInfo().getAuthorization());
            expressRTCameraParam.setUri("/evo-apigw/admin/API/MTS/Video/");
            expressRTCameraParam.setLocation("");
            expressRTCameraParam.setUser_client(6);
            expressRTCameraParam.setUseHttps(CommonInfo.getInstance().getEnvironmentInfo().isHttps() ? 1 : 0);

            return new ExpressRTCamera(expressRTCameraParam);
        } else {
            DPSRTCameraParam dpsrtCameraParam = new DPSRTCameraParam();
            dpsrtCameraParam.setCameraID(channelInfo.getChnSncode());
            try {
                dpsrtCameraParam.setDpHandle(String.valueOf(dataAdapterInterface.getDPSDKEntityHandle()));
            } catch (BusinessException e) {
                e.printStackTrace();
            }
            RealInfo realInfo = new RealInfo();
            int mStreamType = ChannelInfo.ChannelStreamType.getValue(channelInfo.getStreamType());
            if (mStreamType > Stream_Assist_Type) mStreamType = Stream_Assist_Type;
            realInfo.setStreamType(mStreamType);
            realInfo.setMediaType(3);
//            realInfo.setTrackID("601");//设置此处部分设备可能不能播放
            realInfo.setStartChannelIndex(0);
            realInfo.setSeparateNum("1");
            realInfo.setCheckPermission(true);
            dpsrtCameraParam.setRealInfo(realInfo);
            return new DPSRTCamera(dpsrtCameraParam);
        }
    }

    /**
     * 获取当前设备使用的码流加密秘钥
     */
    private void getEncryptKey() {
        AsyncBuilder.createTask(new AsyncBuilder.BusinessTask<VictoryKey>() {
            @Override
            public VictoryKey doInBackground() throws Exception {
                VictoryKey victoryKey = dataAdapterInterface.getCurrentMediaVK(mChannelInfo.getChnSncode().substring(0, mChannelInfo.getChnSncode().indexOf("$")));
                if (victoryKey != null)
                    encryptKey = coverEncryptKey(victoryKey.getVkId(), victoryKey.getVkValue());
                return victoryKey;
            }
        }).resultInMain(this, new AsyncBuilder.ResultListener<VictoryKey>() {
            @Override
            public void onSuccess(VictoryKey victoryKey) {

            }

            @Override
            public void onError(BusinessException e) {

            }
        });
    }

    /**
     * 秘钥转换
     */
    public static String coverEncryptKey(String encryptId, String encryptKey) {
        if (TextUtils.isEmpty(encryptId) || TextUtils.isEmpty(encryptKey)) {
            return "";
        }
        byte[] inId = Base64Utils.decode(encryptId);
        byte[] inKey = Base64Utils.decode(encryptKey);
        byte[] outKey = new byte[inId.length + inKey.length + 1];
        outKey[0] = 0x01;
        for (int i = 0; i < inId.length; i++) {
            outKey[i + 1] = inId[i];
        }
        for (int i = 0; i < inKey.length; i++) {
            outKey[i + inId.length + 1] = inKey[i];
        }
        return Base64Utils.encode(outKey).replaceAll("\n", "");
    }

    /**
     * 开始播放
     */
    private void startPlay(int winIndex) {
        if (getCameras().size() > 0) {
            mPlayManager.addCamera(winIndex, getCameras().get(0));
        }
        mPlayManager.playSingle(winIndex);
    }

    /**
     * 重新播放
     */
    private void replay() {
        mPlayManager.playCurpage();
    }

    /**
     * 停止播放
     */
    private void stopPlay(int winIndex) {
        mPlayManager.stopSingle(winIndex);
    }

    /**
     * 所有窗口停止播放
     */
    private void stopAll() {
        mPlayManager.stopAll();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back) {
            finish();
        } else if (id == R.id.tv_playback) {
            PlayBackActivity.open(this, mChannelInfo);
        } else if (id == R.id.iv_full_screen) {
            switchScreen();
        } else if (id == R.id.tv_screenshots) {
            checkPermission(1);
        } else if (id == R.id.tv_videotape) {
            checkPermission(2);
        } else if (id == R.id.tv_intercom) {
            checkPermission(3);
        } else if (id == R.id.tv_preset_position) {
            showPresetPositionDialog();
        } else if (id == R.id.tv_ptz) {
            onClickPTZ();
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                int id = v.getId();
                if (id == R.id.multiple_subtract) {
                    sendPTZOperation(ChannelInfo.PtzOperation.zoomReduce, false);
                } else if (id == R.id.multiple_add) {
                    sendPTZOperation(ChannelInfo.PtzOperation.zoomAdd, false);
                } else if (id == R.id.focal_length_subtract) {
                    sendPTZOperation(ChannelInfo.PtzOperation.focusReduce, false);
                } else if (id == R.id.focal_length_add) {
                    sendPTZOperation(ChannelInfo.PtzOperation.focusAdd, false);
                } else if (id == R.id.aperture_subtract) {
                    sendPTZOperation(ChannelInfo.PtzOperation.apertureReduce, false);
                } else if (id == R.id.aperture_add) {
                    sendPTZOperation(ChannelInfo.PtzOperation.apertureAdd, false);
                }
                break;
            case MotionEvent.ACTION_UP:
                int vId = v.getId();
                if (vId == R.id.multiple_subtract) {
                    sendPTZOperation(ChannelInfo.PtzOperation.zoomReduce, true);
                } else if (vId == R.id.multiple_add) {
                    sendPTZOperation(ChannelInfo.PtzOperation.zoomAdd, true);
                } else if (vId == R.id.focal_length_subtract) {
                    sendPTZOperation(ChannelInfo.PtzOperation.focusReduce, true);
                } else if (vId == R.id.focal_length_add) {
                    sendPTZOperation(ChannelInfo.PtzOperation.focusAdd, true);
                } else if (vId == R.id.aperture_subtract) {
                    sendPTZOperation(ChannelInfo.PtzOperation.apertureReduce, true);
                } else if (vId == R.id.aperture_add) {
                    sendPTZOperation(ChannelInfo.PtzOperation.apertureAdd, true);
                }
                break;
        }

        return true;
    }

    /**
     * 检查权限
     */
    private void checkPermission(int permissionType) {
        mPermission = permissionType;
        List<String> permissionList = new ArrayList<>();
        switch (permissionType) {
            case 1:
                permissionList.addAll(Arrays.asList(PermissionConstant.STORAGE));
                break;
            case 2:
                permissionList.addAll(Arrays.asList(PermissionConstant.STORAGE));
                permissionList.addAll(Arrays.asList(PermissionConstant.MICROPHONE));
            case 3:
                permissionList.addAll(Arrays.asList(PermissionConstant.MICROPHONE));
                break;
        }
        permissionUtil.requestPermissions(this, permissionList.toArray(new String[0]));
    }

    @Override
    public void onPermissionGranted() {
        switch (mPermission) {
            case 1:
                onClickCapture();
                break;
            case 2:
                onClickVideotape();
                break;
            case 3:
                onClickIntercom();
                break;
        }
    }

    @Override
    public void onPermissionDenied() {

    }

    @Override
    public void onPermissionSetting(boolean b) {

    }

    /**
     * 抓图
     */
    protected void onClickCapture() {
        if (!mPlayManager.isStreamPlayed(mPlayManager.getSelectedWindowIndex())) return;
        int currentWindowIndex = mPlayManager.getSelectedWindowIndex();
        String path = FileStorageUtil.createSnapPath();
        int ret = mPlayManager.snapShot(currentWindowIndex, path, true);
        if (ret == Err.OK) {
            showToast(getResources().getString(R.string.screenshots_success) + path);
            MediaScannerConnection.scanFile(this, new String[]{path}, null, null);
        } else {
            showToast(getResources().getString(R.string.screenshots_failed));
        }
    }

    /**
     * 录像
     */
    protected void onClickVideotape() {
        if (mPlayManager.isRecording(mPlayManager.getSelectedWindowIndex())) {
            int ret = mPlayManager.stopRecord(mPlayManager.getSelectedWindowIndex());
            if (ret == Err.OK) {
                showToast(getString(R.string.recording_end));
                MediaScannerConnection.scanFile(this, recordPath, null, null);
                mTvVideotape.setSelected(false);
            }
        } else {
            if (!mPlayManager.isStreamPlayed(mPlayManager.getSelectedWindowIndex()) || mPlayManager.isPause(mPlayManager.getSelectedWindowIndex()))
                return;
            int currentWindowIndex = mPlayManager.getSelectedWindowIndex();
            recordPath = FileStorageUtil.createRecordPath();
            recordPath[0] = recordPath[0].replaceAll("dav", "mp4");
            int ret = mPlayManager.startRecord(currentWindowIndex, recordPath, RecordType.RECORDER_TYPE_MP4);
            if (ret == Err.OK) {
                showToast(getString(R.string.recording_start));
                MediaScannerConnection.scanFile(getApplicationContext(), recordPath, null, null);
                mTvVideotape.setSelected(true);
            }
        }
    }

    /**
     * 对讲
     */
    protected void onClickIntercom() {
        if (!isPlaying) {
            showToast(getString(R.string.no_intercom_equipment));
            return;
        }
        if (isStartTalk) {
            isStartTalk = false;
            mTvIntercom.setSelected(false);
            if (mPlayManager != null) {
                mPlayManager.stopTalk(0);
            }
        } else {
            if (BuildConfig.dssPlatform == 1) {
                CloudBaseTalkParam cloudBaseTalkParam = new CloudBaseTalkParam();
                cloudBaseTalkParam.setCameraID(mChannelInfo.getChnSncode().substring(0, mChannelInfo.getChnSncode().indexOf("$")));
                UserInfo mUserInfo = CommonInfo.getInstance().getUserInfo();
                cloudBaseTalkParam.setDpRestToken((String) mUserInfo.getExtandAttributeValue("token"));
                cloudBaseTalkParam.setServerIp(SPUtils.getString(Config.IP, ""));
                cloudBaseTalkParam.setServerPort(Integer.parseInt(SPUtils.getString(Config.PORT, "")));
                cloudBaseTalkParam.setTalkType(1);
                cloudBaseTalkParam.setTransMode(1);
                cloudBaseTalkParam.setSampleRate(TalkParam.AUDIO_SAMPLE_RATE_8000);
                cloudBaseTalkParam.setSampleDepth(TalkParam.AUDIO_SAMPLE_DEPTH_16);
                cloudBaseTalkParam.setEncodeType(TalkParam.AUDIO_ENCODE_G711A);
                cloudBaseTalkParam.setUseHttps(CommonInfo.getInstance().getEnvironmentInfo().isHttps() ? 1 : 0);
                cloudBaseTalkParam.setRoute(false);
                cloudBaseTalkParam.setUserId("");
                cloudBaseTalkParam.setDomainId("");
                cloudBaseTalkParam.setRegionId("");

                CloudBaseTalk talk = new CloudBaseTalk(cloudBaseTalkParam);
                if (mPlayManager.startTalk(0, talk) == 0) {
                    isStartTalk = true;
                    mTvIntercom.setSelected(true);
                } else {
                    isStartTalk = false;
                    mTvIntercom.setSelected(false);
                    showToast(getString(R.string.intercom_failed));
                }
            } else if (BuildConfig.dssPlatform == 2) {
                ExpressTalkParam expressTalkParam = new ExpressTalkParam();
                expressTalkParam.setCameraID(mChannelInfo.getChnSncode().substring(0, mChannelInfo.getChnSncode().indexOf("$")));
                expressTalkParam.setDpRestToken(CommonInfo.getInstance().getEnvironmentInfo().getRestToken());
                expressTalkParam.setServerIp(SPUtils.getString(Config.IP, ""));
                expressTalkParam.setServerPort(Integer.parseInt(SPUtils.getString(Config.PORT, "")));
                expressTalkParam.setAuthorization(CommonInfo.getInstance().getEnvironmentInfo().getAuthorization());
                expressTalkParam.setUri("/evo-apigw/admin/API/MTS/Audio/");
                expressTalkParam.setUser_client(6);
                expressTalkParam.setReset(0);
                expressTalkParam.setTalkType(1);
                expressTalkParam.setTransMode(1);
                expressTalkParam.setSampleRate(TalkParam.AUDIO_SAMPLE_RATE_8000);
                expressTalkParam.setSampleDepth(TalkParam.AUDIO_SAMPLE_DEPTH_16);
                expressTalkParam.setEncodeType(TalkParam.AUDIO_ENCODE_G711A);
                ExpressTalk talk = new ExpressTalk(expressTalkParam);
                mPlayManager.setOnTalkListener(new ITalkListener() {
                    @Override
                    public void onTalkResult(int winIndex, TalkResultType talkResultType, String code, int type) {

                    }
                });
                if (mPlayManager.startTalk(0, talk) == 0) {
                    isStartTalk = true;
                    mTvIntercom.setSelected(true);
                } else {
                    isStartTalk = false;
                    mTvIntercom.setSelected(false);
                    showToast(getString(R.string.intercom_failed));
                }

            } else {
                DPSTalkParam dpsTalkParam = new DPSTalkParam();
                dpsTalkParam.setCameraID(mChannelInfo.getChnSncode().substring(0, mChannelInfo.getChnSncode().indexOf("$")));
                try {
                    dpsTalkParam.setDpHandle(String.valueOf(dataAdapterInterface.getDPSDKEntityHandle()));
                } catch (BusinessException e) {
                    e.printStackTrace();
                }
                dpsTalkParam.setEncodeType(TalkParam.AUDIO_ENCODE_G711A);
                dpsTalkParam.setSampleDepth(TalkParam.AUDIO_SAMPLE_DEPTH_16);
                dpsTalkParam.setSampleRate(TalkParam.AUDIO_SAMPLE_RATE_8000);
                dpsTalkParam.setTalkType(1);
                dpsTalkParam.setTransMode(1);
                DPSTalk talk = new DPSTalk(dpsTalkParam);
                if (mPlayManager.startTalk(0, talk) == 0) {
                    isStartTalk = true;
                    mTvIntercom.setSelected(true);
                } else {
                    isStartTalk = false;
                    mTvIntercom.setSelected(false);
                    showToast(getString(R.string.intercom_failed));
                }
            }

        }
    }

    /**
     * 云台
     */
    protected void onClickPTZ() {
        if (mPlayManager == null || !mPlayManager.isStreamPlayed(mPlayManager.getSelectedWindowIndex()))
            return;
        int windowIndex = mPlayManager.getSelectedWindowIndex();
        if (!mPlayManager.isPlaying(windowIndex)) return;
        if (mPlayManager.isOpenPTZ(windowIndex)) {
            if (mPlayManager.setPTZEnable(windowIndex, false) == Err.OK) {
                mTvPtz.setSelected(false);
                mNestedScrollView.setVisibility(View.GONE);
            }
        } else {
            if (mPlayManager.setPTZEnable(windowIndex, true) == Err.OK) {
                mTvPtz.setSelected(true);
                mNestedScrollView.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * 云台控制
     */
    protected void sendPTZOperation(final ChannelInfo.PtzOperation operation, final boolean isStop) {
        AsyncBuilder.createTask(new AsyncBuilder.BusinessTask<Integer>() {
            @Override
            public Integer doInBackground() throws Exception {
                /**
                 * var1 操作类型（变焦、光圈、焦距...）
                 * var2 uuid
                 * var3 云台步长
                 * var4 操作是否结束
                 */
                return DataAdapterImpl.getInstance().operatePTZ(operation, mChannelInfo.getUuid(), 4, isStop);
            }
        }).resultInMain(this, new AsyncBuilder.ResultListener<Integer>() {
            @Override
            public void onSuccess(Integer integer) {

            }

            @Override
            public void onError(BusinessException e) {

            }
        });
    }

    public ChannelInfo.PtzOperation getPtzOperation(PtzOperation oprType){
        ChannelInfo.PtzOperation operation              = ChannelInfo.PtzOperation.stop;
        if(oprType == PtzOperation.up)        operation = ChannelInfo.PtzOperation.up;
        if(oprType == PtzOperation.down)      operation = ChannelInfo.PtzOperation.down;
        if(oprType == PtzOperation.left)      operation = ChannelInfo.PtzOperation.left;
        if(oprType == PtzOperation.right)     operation = ChannelInfo.PtzOperation.right;
        if(oprType == PtzOperation.leftUp)    operation = ChannelInfo.PtzOperation.leftUp;
        if(oprType == PtzOperation.leftDown)  operation = ChannelInfo.PtzOperation.leftDown;
        if(oprType == PtzOperation.rightUp)   operation = ChannelInfo.PtzOperation.rightUp;
        if(oprType == PtzOperation.rightDown) operation = ChannelInfo.PtzOperation.rightDown;
        return operation;
        // 若想用摄像头的放大和缩小，operation可以按如下设置：
        // operation = ChannelInfo.PtzOperation.zoomAdd; 放大
        // operation = ChannelInfo.PtzOperation.zoomReduce;缩小
    }
    /**
     * 预置点弹窗
     */
    private void showPresetPositionDialog() {
        Bundle bundle = new Bundle();
        bundle.putSerializable("channelInfo", mChannelInfo);
        PresetPositionDialogFragment.getInstance(bundle).show(getSupportFragmentManager(), "presetPosition");
    }


    /**
     * 初始化视频窗口
     */
    public void initCommonWindow() {
        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mPlayWindow.getLayoutParams();
        lp.width = isFull ? mScreenHeight : mScreenWidth;
        lp.height = isFull ? mScreenWidth : mScreenHeight / 3;
        mPlayWindow.setLayoutParams(lp);
        mPlayWindow.forceLayout(lp.width, lp.height);
    }

    /**
     * 切换横竖屏
     */
    public void switchScreen() {
        if (isFull) {
            isFull = false;
            mClTitle.setVisibility(View.VISIBLE);
            mIvFullScreen.setImageResource(R.mipmap.icon_full_screen);
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        } else {
            isFull = true;
            mClTitle.setVisibility(View.GONE);
            mIvFullScreen.setImageResource(R.mipmap.icon_exit_full_screen);
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
        }
        initCommonWindow();
    }


    @Override
    public void onBackPressed() {
        if (isFull) {
            switchScreen();
        } else {
            this.finish();
        }
    }


    private IMediaPlayListener iMediaPlayListener = new IMediaPlayListener() {
        @Override
        public void onPlayeStatusCallback(int winIndex, PlayStatusType type, int code) {
            Message msg = Message.obtain();
            msg.obj = winIndex;
            if (type == PlayStatusType.eStreamPlayed) {
                msg.what = KEY_Handler_Stream_Played;
                if (mPlayOnlineHander != null) mPlayOnlineHander.sendMessage(msg);
            } else if (type == PlayStatusType.ePlayFirstFrame) {
                msg.what = KEY_Handler_First_Frame;
                if (mPlayOnlineHander != null) mPlayOnlineHander.sendMessage(msg);
            } else if (type == PlayStatusType.eNetworkaAbort) {
                msg.what = KEY_Handler_Net_Error;
                if (mPlayOnlineHander != null) mPlayOnlineHander.sendMessage(msg);
            } else if (type == PlayStatusType.ePlayFailed) {
                msg.what = KEY_Handler_Play_Failed;
                if (mPlayOnlineHander != null) mPlayOnlineHander.sendMessage(msg);
            }
        }
    };

    private IOperationListener iOperationListener = new IOperationListener() {
        @Override
        public void onWindowSelected(int position) {
            Log.d(TAG, "onWindowSelected" + position);
        }

        @Override
        public void onPageChange(int newPage, int prePage, int type) {
            Log.d(TAG, "onPageChange" + newPage + prePage + type);
            if (type == 0) {
                if (mPlayManager.getPageCellNumber() == 1) {
                    mPlayManager.setEZoomEnable(prePage, false);
                    mPlayManager.setEZoomEnable(newPage, true);
                }
            }
        }

        @Override
        public void onSplitNumber(int nCurCellNumber, int nCurPage, int nPreCellNumber, int nPrePage) {
            Log.d(TAG, "onSplitNumber" + nCurCellNumber);
        }

        @Override
        public void onControlClick(int nWinIndex, ControlType type) {
            Log.d(TAG, "onControlClick" + type);
            if (type == ControlType.Control_Reflash) {
                startPlay(nWinIndex);
            }
        }

        @Override
        public void onSelectWinIndexChange(int newWinIndex, int oldWinIndex) {
            Log.d(TAG, "onSelectWinIndexChange:" + newWinIndex + ":" + oldWinIndex);
            if (!mPlayManager.hasTalking()) {
                if (mPlayManager.isOpenAudio(oldWinIndex)) {
                    mPlayManager.closeAudio(oldWinIndex);
                    mPlayManager.setNeedOpenAudio(oldWinIndex, true);
                }

                if (mPlayManager.isPlaying(newWinIndex) && mPlayManager.isNeedOpenAudio(newWinIndex))
                    mPlayManager.openAudio(newWinIndex);
            }
        }

        @Override
        public void onWindowDBClick(int winIndex, int type) {
            Log.d(TAG, "onWindowDBClick" + type + " winIndex:" + winIndex + " isWindowMax:" + mPlayManager.isWindowMax(winIndex));
            if (mPlayManager.isOpenPTZ(winIndex)) {
                if (mPlayManager.setPTZEnable(winIndex, false) == Err.OK) {
                    mPlayManager.setResumeFlag(winIndex, false);
                }
            }
            mPlayManager.setEZoomEnable(winIndex, type == 0);
        }

        @Override
        public void onMoveWindowBegin(int winIndex) {
            Log.d(TAG, "onMoveWindowBegin");
        }

        @Override
        public void onMovingWindow(int winIndex, float x, float y) {
            Log.d(TAG, "onMovingWindow x:" + x + " y:" + y);
        }

        @Override
        public boolean onMoveWindowEnd(int winIndex, float x, float y) {
            Log.d(TAG, "onMoveWindowEnd x:" + x + " y:" + y);
            return false;
        }
    };

    private IPTZListener iptzListener = new IPTZListener() {
        @Override
        public void onPTZControl(int winIndex, PtzOperation oprType, boolean isStop, boolean isLongPress) {
            sendPTZOperation(getPtzOperation(oprType), isStop);
        }

        @Override
        public void onPTZZooming(int winIndex, float scale, PtzOperation oprType, PtzZoomState state) {

        }
    };

}
